package com.bawei.module_visitor.adapter

import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.content.ContextCompat
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bawei.lib_common.base.BaseApplication
import com.bawei.module_visitor.R
import com.bawei.module_visitor.model.VisitorModelItem
import com.bawei.module_visitor.model.VisitorStateModel

class VisitorAdapter(
    private val onStateItemClick: ((id: Int) -> Unit)? = null
): RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    companion object {
        const val TYPE_VISITOR_STATE = 0
        const val TYPE_VISITOR = 1
    }
    private val visitorItems= mutableListOf<VisitorModelItem>()
    private val stats= mutableListOf<VisitorStateModel> ()
    // 添加选中状态追踪变量，初始值为-1表示未选中，0表示默认选中第一个状态项
    private var selectedStatePosition: Int = 0  // 默认选中第一个状态项
    fun setSelectedStatePosition(position: Int) {
        if (position in 0 until stats.size) {
            val previousPosition = selectedStatePosition
            selectedStatePosition = position
            notifyItemChanged(previousPosition)
            notifyItemChanged(position)
        }
    }
    fun setVisitorData(data:List<VisitorModelItem>){
        visitorItems.clear()
        visitorItems.addAll(data)
        notifyDataSetChanged()
    }
    fun setStatisticsData(data:List<VisitorStateModel>){
        stats.clear()
        stats.addAll(data)  //
        notifyDataSetChanged()
    }
    override fun getItemViewType(position: Int): Int {
        // 统计项的位置固定为功能项数量（仅当统计项存在时）
        return if (position < stats.size) {
            TYPE_VISITOR_STATE
        } else {
            TYPE_VISITOR
        }
    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return when (viewType) {
            TYPE_VISITOR_STATE -> {
                val view = LayoutInflater.from(parent.context).inflate(R.layout.item_visit_status, parent, false)
                StatsViewHolder(view)
            }
            TYPE_VISITOR -> {
                val view = LayoutInflater.from(parent.context).inflate(R.layout.item_visit, parent, false)
                VisitorViewHolder(view)
            }
            else -> throw IllegalArgumentException("未知的视图类型")
        }
    }

    override fun getItemCount(): Int {
        return stats.size + visitorItems.size
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        when (holder) {
            is StatsViewHolder -> {
                val item = stats[position]
                holder.visitorStateTitle.text = item.state
                // 根据是否选中设置不同的背景和文字颜色
                if (position == selectedStatePosition) {
                    // 选中状态
                    holder.itemView.setBackgroundResource(android.R.color.transparent) // 需要创建这个drawable资源
                    holder.visitorStateTitle.setTextColor(ContextCompat.getColor(BaseApplication.instance, com.bawei.lib_common.R.color.blue)) // 使用蓝色
                } else {
                    // 未选中状态
                    holder.itemView.setBackgroundResource(android.R.color.transparent) // 或者使用默认背景
                    holder.visitorStateTitle.setTextColor(ContextCompat.getColor(BaseApplication.instance, android.R.color.black)) // 使用默认黑色
                }
                holder.itemView.setOnClickListener {
                    onStateItemClick?.invoke(item.id)
                }
            }
            is VisitorViewHolder -> {
                val visitorPosition = position - stats.size
                val item = visitorItems[visitorPosition]
                val colorRes = when (item.visitStatus) {
                    "待审核" -> com.bawei.lib_common.R.color.color_yellow_dark
                    "已通过" -> com.bawei.lib_common.R.color.color_40b223
                    "已完成" -> com.bawei.lib_common.R.color.color_40b228
                    "驳回" -> com.bawei.lib_common.R.color.color_examine_red
                    else -> android.R.color.black // 默认颜色
                }
                when (item.visitStatus) {
                    "待审核" -> holder.visitState.setBackgroundResource(R.drawable.shape_item_repair_one)
                    "已通过" -> holder.visitState.setBackgroundResource(R.drawable.shape_item_repair_there)
                    "已完成" -> holder.visitState.setBackgroundResource(R.drawable.shape_item_repair_five)
                    "驳回" -> holder.visitState.setBackgroundResource(R.drawable.shape_item_repair_four)
                    else -> android.R.color.black // 默认颜色
                }
                holder.visitState.setTextColor(ContextCompat.getColor(BaseApplication.instance, colorRes))
                holder.visitTime.text = item.appointmentTime
                holder.visitState.text = item.visitStatus
                holder.visitName.text = item.visitorName
                holder.visitPhoneNum.text = item.phoneNumber
                holder.visitPurpose.text = item.purpose
                holder.visitEmployeeId.text = item.employeeId.toString()
                if(item.requestParking){
                    holder.visitCar.setImageResource(R.drawable.visit_item_car_yes)
                    holder.visitRequestParking.text = "已申请访客车位：A区-12号"
                    holder.visitRequestParking.setTextColor(Color.parseColor("#1E88E5"))
                }else{
                    holder.visitCar.setImageResource(R.drawable.visit_item_car_no)
                    holder.visitRequestParking.text = "未申请访客车位"
                    holder.visitRequestParking.setTextColor(Color.parseColor("#9CA3AF"))
                }

            }
         }
    }
    class VisitorViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val visitTime: TextView = view.findViewById(R.id.visit_time)
        val visitState: TextView = view.findViewById(R.id.visit_status)
        val visitName: TextView = view.findViewById(R.id.visit_name)
        val visitPhoneNum: TextView = view.findViewById(R.id.visit_phone_num)
        val visitPurpose: TextView = view.findViewById(R.id.visit_purpose)
        val visitEmployeeId: TextView = view.findViewById(R.id.visit_employeeId)
        val visitCar: ImageView = view.findViewById(R.id.visit_item_car)
        val visitRequestParking: TextView = view.findViewById(R.id.visit_request_parking)
    }


    class StatsViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val visitorStateTitle: TextView = view.findViewById(R.id.visit_status_title)
    }
    fun setupLayoutManager(recyclerView: RecyclerView) {
        val layoutManager = GridLayoutManager(recyclerView.context, 5)
        layoutManager.spanSizeLookup = object : GridLayoutManager.SpanSizeLookup() {
            override fun getSpanSize(position: Int): Int {
                return when (getItemViewType(position)) {
                    TYPE_VISITOR_STATE->1
                    else -> 5
                }
            }
        }
        recyclerView.layoutManager = layoutManager
        // 添加间距装饰（水平间距16dp，垂直间距8dp）
        val spacing = recyclerView.context.resources.getDimensionPixelSize(R.dimen.grid_spacing)
        recyclerView.addItemDecoration(GridSpaceItemDecoration(
            horizontalSpacing = spacing,  // 水平间距（左右）
            verticalSpacing = spacing / 2 // 垂直间距（上下，可根据需求调整）
        ))
        // 可选：启用预加载（提升滑动流畅性）
        recyclerView.setItemViewCacheSize(20)
    }
}